﻿
/***AJAX请求***/
function HttpAjax(url, param, method, dataType, func) {
    $.ajax({
        type: method,
        url: url,
        dataType: dataType,
        data: param,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            func({ "status": 200, "data": data });
        },
        error: function (jqXHR) {
            func({ "status": 500, "data": "请求失败：" + jqXHR.status });
        }
    });
}
function CamHttpAjax(url, param, method, dataType, func) {
    $.ajax({
        type: method,
        url: url,
        dataType: dataType,
        data: param,
        contentType: "text/plain",
        headers: { "Content-Type": "text/plain" },
        success: function (data) {
            func({ "status": 200, "data": data });
        },
        error: function (jqXHR) {
            func({ "status": 500, "data": "请求失败：" + jqXHR.status });
        }
    });
}
function LoninToken(fun) {
    $.ajax({
        type: "POST",
        url: __JDURL + "/Login/GetToken",
        dataType: "JSON",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify( {
            "userName": "jd-ddc01",
            "pwd": "jdmap@2012"
        }),

        success: function (data) {
            console.log(data);
            fun(data);
        },
        error: function (jqXHR) {
           console.log(jqXHR);
        }
    });

}

var __JDURL = "http://10.36.80.9:33033";
/***AJAX请求***/
function JDHttpAjax(url, param, method, dataType,tokent, func) {
    $.ajax({
        type: method,
        url: __JDURL + url,
        dataType: dataType,
        data: JSON.stringify(param),
        contentType: "application/json; charset=utf-8",
        headers: { "Authorization": tokent },
        success: function (data) {
            func({ "status": 200, "data": data });
        },
        error: function (jqXHR) {
            func({ "status": 500, "data": "请求失败：" + jqXHR.status });
        }
    });
}

function HttpAjaxProc(url, param, method, dataType, func) {
    $.ajax({
        type: method,
        url: url,
        dataType: dataType,
        data: param,
        processData: false,   // 不处理发送的数据
        contentType: false,   // 不设置Content-Type请求头
        success: function (data) {
            func({ "status": 200, "data": data });
        },
        error: function (jqXHR) {
            func({ "status": jqXHR.status, "data": jqXHR.responseText });
        }
    });
}
/**  tabel 查询**/
function M_Query() {
    $("input[name='query']").bind("input propertychange", function () {
        var sv = $(this).val();
        if (sv == null || sv == "") {
            return;
        }
        var xds = $("#table_tbody tr");
        for (var i = 0; i < xds.length; i++) {
            var tditem = xds[i];
            $(tditem).removeClass("trEd");
            var varr = tditem.innerText.trim().split(sv);
            if (varr.length > 1) {
                // $(tditem).insertBefore($("#table_tbody tr:eq(0)"));
                $(tditem).addClass("trEd");
                $("#table_tbody").prepend($(tditem));
                break;
            }
        }
        $("#table_tbody tr").scrollTop(0);
    });
}
/****导出表格**/
function fn_xml_format(tr_arr_string, sheet_name) {
    var template = '<html xmlns:v=3D"urn:schemas-microsoft-com:vml" xmlns:o=3D"urn:schemas-microsoft-com:office:office" xmlns:x=3D"urn:schemas-microsoft-com:office:excel" xmlns=3D"http://www.w3.org/TR/REC-html40\"><head><xml><o:DocumentProperties><o:Author>yp</o:Author><o:LastAuthor>yp</o:LastAuthor><o:Created>{date_time1}</o:Created><o:LastSaved>{date_time}</o:LastSaved><o:Company>宁波泰禾智能科技有限公司</o:Company><o:Version>1.0</o:Version></o:DocumentProperties></xml><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{sheet_name}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body><table>{table1}</table></body></html>';
    var dt = new Date().toLocaleDateString();
    var data = { "sheet_name": sheet_name, "date_time": dt, "date_time1": dt, "table1": tr_arr_string };
    var format = function (c) {
        return template.replace(/{(\w+)}/g,
            function (m, p) {
                return c[p];
            })
    }
    return format(data);
}
function fn_create_xls(tr_arr_data, sheet_name) {
    var base64 = function (str) {
        return window.btoa(unescape(encodeURIComponent(str)));
    }
    window.location.href = 'data:application/vnd.ms-excel;base64,' + base64(fn_xml_format(tr_arr_data, sheet_name));
}

/*
*获取地址栏参数
*/
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

/**操作成功提示框**/
function msgSuccess(txt, func) {
    window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.success,
        {
            onOk: function () {
                func();
            }
        });

}
/****选项提示框***/
function msgRemind(txt, func) {
    window.wxc.xcConfirm(txt, window.wxc.xcConfirm.typeEnum.confirm, {
        onOk: function () {
            func("true");
        },
        onCancel: function () {
            func("false");
        }
    });

}

function setSelect(tableName, ided, id, name) {

    HttpAjax("../CS/GetDataAPI.ashx", { "title": "query", "tableName": tableName }, "GET", "JSON", function (rdata) {

        var html = "<input type='hidden' value='" + ided + "' name='" + name + "'><select>";
        var data = rdata.data;
        for (var i = 0; i < data.length; i++) {
            if (data[i][id] == ided) {
                html += "<option value='" + data[i][id] + "' selected>" + data[i][name] + "<option>";
            } else {
                html += "<option value='" + data[i][id] + "'>" + data[i][name] + "<option>";
            }
        }
        html += "</select>"

        return html;
    });

}
//  下拉
/// data:数据,ided:选中的数据，id:字段，name:字段，nameIdEd：当前赋值的字段
function selectDataSet(data, ided, id, name, nameIdEd) {
    if (ided == 0) {
        ided = data[0][id];
    }
    var html = "<input type='hidden' value='" + ided + "' name='" + nameIdEd + "'><select name='" + nameIdEd + "'>";
    for (var i = 0; i < data.length; i++) {
        if (data[i][id] == ided) {
            html += "<option value='" + data[i][id] + "' selected>" + data[i][name] + "</option>";
        } else {
            html += "<option value='" + data[i][id] + "'>" + data[i][name] + "</option>";
        }
    }
    html += "</select>";
    return html;
}

function getThisDate() {

    var dictTime = new Date();
    var changeDate = dictTime.getFullYear() + '-' + (dictTime.getMonth() + 1) + '-' + dictTime.getDate() + ' ' + dictTime.getHours() + ':' + dictTime.getMinutes() + ':' + dictTime.getSeconds();

    return changeDate;
}
String.prototype.format = function (args) {
    var result = this;
    for (var i = 0; i < arguments.length; i++) {
        if (arguments[i] == undefined) {
            arguments[i] = "";
        }
    }
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};

function getThisUTLDATE() {

    var dictTime = new Date();
    return Date.UTC(dictTime.getFullYear(), (dictTime.getMonth() + 1), dictTime.getDate(), dictTime.getHours(), dictTime.getMinutes(), dictTime.getSeconds());
}
function DragDIV(id) {
    //获取元素
    var dv = document.getElementById(id);
    var x = 0;
    var y = 0;
    var l = 0;
    var t = 0;
    var isDown = false;
    //鼠标按下事件
    dv.onmousedown = function (e) {
        //获取x坐标和y坐标
        x = e.clientX;
        y = e.clientY;

        //获取左部和顶部的偏移量
        l = dv.offsetLeft;
        t = dv.offsetTop;
        //开关打开
        isDown = true;
        //设置样式  
        dv.style.cursor = 'move';
    }
    //鼠标移动
    window.onmousemove = function (e) {
        if (isDown == false) {
            return;
        }
        //获取x和y
        var nx = e.clientX;
        var ny = e.clientY;
        //计算移动后的左偏移量和顶部的偏移量
        var nl = nx - (x - l);
        var nt = ny - (y - t);

        dv.style.left = nl + 'px';
        dv.style.top = nt + 'px';
    }
    //鼠标抬起事件
    dv.onmouseup = function () {
        //开关关闭
        isDown = false;
        dv.style.cursor = 'default';
    }

}


function __loadFBX(fileInput, OnBack,token) {
    //选择文件
    $(fileInput[0]).click();
    var thisDom = fileInput;
    fileInput.on('change', function () {
        //如果未传入文件则中断
        if (fileInput[0].files[0] == undefined) {
            return;
        } else {

            // del(fileName);
        }
        var file = fileInput[0].files[0];
        var formData = new FormData();
        formData.append("file", file)
        var xhr = new XMLHttpRequest();
        //post方式
        xhr.open('POST', __JDURL + '/api/JD/UploadFile/AB');
        xhr.setRequestHeader("Authorization", token);
        //监听上传事件
        if (xhr.upload) {
            //监听上传属性的上传事件,
            xhr.upload.addEventListener('progress', progressHandlingFunction, false);
        }
        //发送请求
        xhr.send(formData);
        //ajax返回
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
            }
        };
        //设置超时时间
        xhr.timeout = 1000 * 60*60*60;
        xhr.ontimeout = function (event) {
            alert('请求超时！');
        }


    });

    //上传监听 回调
    function progressHandlingFunction(event) {
        event.total;        //获取上传文件的总大小
        event.loaded;        //获取已经上传的文件大小
        //获取进度的百分比值
        let percent = (event.loaded / event.total) * 100;

        //四舍五入保留0位小数
        percent = percent.toFixed(0);
        OnBack(percent);
        // thisClickDomInput.next().text("进度：" + percent + "%");
        if (percent == 100) {

            // thisClickDomInput.next().text("上传成功");
        }
    }
}
